package com.orange.core.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class ExcelUtil {

    public static <T> void write(List<T> records, Class<T> tClass, HttpServletResponse response, String name) throws IOException {
        setHeader(response, name);
        // 这里需要设置不关闭流
        EasyExcel.write(response.getOutputStream(), tClass)
                .autoCloseStream(Boolean.FALSE)
                .sheet("sheet1")
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(records);
    }

    @SneakyThrows
    public static void write(Workbook workbook, HttpServletResponse response, String name) {
        setHeader(response, name);
        // 将工作簿写入文件并关闭工作簿
        workbook.write(response.getOutputStream()); // 将工作簿写入文件
        workbook.close(); // 关闭工作簿
    }

    public static void setHeader(HttpServletResponse response, String name) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(name, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
    }
}
